<template>
  <view class="container">
    <view class="form">
      <view class="input-group">
        <text class="label">用户名</text>
        <input 
          v-model="username" 
          class="input" 
          type="text" 
          placeholder="请输入用户名" 
        />
      </view>
      
      <view class="input-group">
        <text class="label">密码</text>
        <input 
          v-model="password" 
          class="input" 
          type="password" 
          placeholder="请输入密码" 
        />
      </view>

      <button class="register-btn" @click="handleRegister">注册</button>
      
      <view v-if="errorMessage" class="error-message">
        <text>{{ errorMessage }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',  // 用户名
      password: '',  // 密码
      errorMessage: '',  // 错误信息
    };
  },
  methods: {
    // 注册逻辑
    handleRegister() {
      // 清空错误信息
      this.errorMessage = '';

      // 前端表单验证
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }

      // 请求后端的注册接口
      uni.request({
        url: 'http://localhost:3000/register',  // 后端注册接口地址
        method: 'POST',
        data: {
          username: this.username,
          password: this.password,
        },
        success: (res) => {
          if (res.data.success) {
            uni.showToast({
              title: '注册成功',
              icon: 'success',
            });
            uni.navigateTo({
              url: '/pages/login/login',  // 注册成功后跳转到登录页面
            });
          } else {
            // 注册失败
            this.errorMessage = res.data.message || '注册失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);  // 打印请求错误，便于调试
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.form {
  width: 80%;
  max-width: 400px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.input-group {
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  margin-bottom: 8px;
}

.input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.register-btn {
  width: 100%;
  padding: 12px;
  background-color: #007aff;
  color: white;
  border-radius: 6px;
  font-size: 16px;
  border: none;
}

.error-message {
  color: red;
  margin-top: 10px;
}
</style>
